#include "ftp.h"

/**
 * @param sockfd 
 * @param recvbuf
 * @param maxlen
 *
 * @return -1 if error occur or time out
 * @return the response code
 */
int res_from_server(int sockfd,char *recvbuf,int maxlen) {
	char buf[MAXLINE];
	int code;
	int ret;

	/*
	ret = readable_timeout(sockfd);
	if(ret == -1) {
		MSG("readable_timeout failed");
		return -1;
	}
	else if(ret == 0) {
		MSG("res_from_server timeout");
		return -1;
	}
	*/

	ret = readline_timeout(sockfd,buf,MAXLINE);
	if(ret == -1) {
		MSG("readline_timeout failed");
		return -1;
	}
	else if(ret == 0) {
		MSG("res_from_server:reach EOF unexpectedly");
		return -1;
	}

	run_log("%s",buf);
	sscanf(buf,"%d",&code);
	if(buf[3] == '-') {
		while(1) {
			/*
			ret = readable_timeout(sockfd);
			if(ret == -1) {
				MSG("readable_timeout failed");
				return -1;
			}
			else if(ret == 0) {
				MSG("res_from_server timeout");
				return -1;
			}
			*/

			ret = readline_timeout(sockfd,buf,MAXLINE);
			if(ret == -1) {
				MSG("readline_timeout failed");
				return -1;
			}
			else if(ret == 0) {
				MSG("res_from_server:reach EOF unexpectedly");
				return -1;
			}

			run_log("%s",buf);
			if(atoi(buf) == code && buf[3] == ' ')
				break;
		} 
	}

	if(recvbuf != NULL)
		strncpy(recvbuf,buf,maxlen);

	return code;
}

int cmd_to_server(int sockfd,const char* cmd) {
	int ret;
	//printf("--> %s\n",cmd);
	run_log("--> %s",cmd);
	ret = writen(sockfd,(void *)cmd,strlen(cmd));
	if(ret == -1) {
		MSG("writen failed:%s",cmd);
		return -1;
	}

	return 0;
}
